import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class testwork1 {

    public static List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> map1 = new HashMap<>();
        int x = 0;
        for (String s : words) {
            if (!map1.containsKey(s)) {
                map1.put(s, 1);
                x++;
            } else {
                map1.put(s, map1.get(s) + 1);
            }
            //map1.put(s,map1.getOrDefault(s,0)+1);
        }
       List<String> list=new ArrayList<>();
        for(Map.Entry<String,Integer>integerEntry:map1.entrySet()){
            list.add(integerEntry.getKey());
        }
        //利用自定义list的排序原理
        Collections.sort(list, new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        return map1.get(o1)==map1.get(o2) ? o1.compareTo(o2):map1.get(o2)-map1.get(o1);//o1-o2升序
                    }
                });
        return list.subList(0,k);
    }

    public static void main(String[] args) {
        String[]arr={"i","love","leetcode","i","love","coding"};
        List<String>list=new ArrayList<>();
        list=topKFrequent(arr,2);
        System.out.println(list.toString());
    }
}

